import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/components/Login'
import Home from '@/components/Home'
import Welcome from '@/components/Welcome'
import Users from '@/components/user/Users'

Vue.use(Router)

const router = new Router({
  routes: [{path: '/login', component: Login}, {path: '/', redirect: '/login'}, {
    path: '/home', component: Home, redirect: '/welcome', children: [{path: '/welcome', component: Welcome},{path:'/users',component:Users}]
  }]
})

//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转过来的
  // next 是一个函数,表示放行

  //如果用户请求的是登录页面
  if (to.path === '/login') {
    return next();
  }
  // 从sessionStorage获取token
  const tokenStr = window.sessionStorage.getItem('token')

  // 如果 tokenStr 是 null 代表 false
  if (!tokenStr) {
    // 没有token 跳转到登录页面
    return next('/login');
  } else {
    return next();
  }

})

export default router
